﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


using System;
using Tesla.Content;
using Tesla.Core;
using Tesla.Graphics.Implementation;

namespace Tesla.Graphics {
    
    /// <summary>
    /// Represents the indices of vertices in a vertex buffer. This allows for
    /// vertex data to be re-used, if duplicate vertices exists which allows for
    /// a smaller vertex buffer (thus saving space).
    /// </summary>
    public class IndexBuffer : GraphicsResource, ISavable {
        private IndexBufferImplementation _impl;

        /// <summary>
        /// Get the underlying index buffer implementation.
        /// </summary>
        public override GraphicsResourceImplementation Implementation {
            get {
                return _impl;
            }
        }

        /// <summary>
        /// Get the number of indices in the buffer.
        /// </summary>
        public int IndexCount {
            get {
                return _impl.IndexCount;
            }
        }

        /// <summary>
        /// Get the index format, 32 (int) or 16 (short).
        /// </summary>
        public IndexFormat IndexFormat {
            get {
                return _impl.IndexFormat;
            }
        }

        /// <summary>
        /// Get the buffer usage, either static or dynamic.
        /// </summary>
        public ResourceUsage BufferUsage {
            get {
                return _impl.BufferUsage;
            }
        }

        /// <summary>
        /// For ISavable.
        /// </summary>
        protected IndexBuffer() {}

        /// <summary>
        /// Creates a new instance of <see cref="IndexBuffer"/>.
        /// </summary>
        /// <param name="format">The index format.</param>
        /// <param name="indexCount">The number of indices the buffer will contain.</param>
        /// <param name="usage">The resource usage specifying the type of memory the buffer should use.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying buffer fails.</exception>
        public IndexBuffer(IndexFormat format, int indexCount, ResourceUsage usage) {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateIndexBufferImplementation(format, indexCount, usage);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="IndexBuffer"/>.
        /// </summary>
        /// <param name="data">The index data.</param>
        /// <param name="usage">The resource usage specifying the type of memory the buffer should use.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating underlying buffer fails or the render system
        /// was not initialized.</exception>
        public IndexBuffer(DataBuffer<int> data, ResourceUsage usage) {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateIndexBufferImplementation(data, usage);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="IndexBuffer"/>.
        /// </summary>
        /// <param name="data">The index data.</param>
        /// <param name="usage">The resource usage specifying the type of memory the buffer should use.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating underlying buffer fails or the render system
        /// was not initialized.</exception>
        public IndexBuffer(DataBuffer<short> data, ResourceUsage usage) {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;
            try {
                _impl = renderSystem.CreateIndexBufferImplementation(data, usage);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }




        /// <summary>
        /// Creates a new instance of <see cref="IndexBuffer"/>.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <param name="format">The index format.</param>
        /// <param name="indexCount">The number of indices the buffer will contain.</param>
        /// <param name="usage">The resource usage specifying the type of memory the buffer should use.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the render system is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating underlying buffer fails.</exception>
        public IndexBuffer(IRenderSystemProvider renderSystem, IndexFormat format, int indexCount, ResourceUsage usage) {
            if(renderSystem == null) {
                Dispose();
                throw new ArgumentNullException("renderSystem", "Render system cannot be null.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateIndexBufferImplementation(format, indexCount, usage);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="IndexBuffer"/>.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <param name="data">The index data.</param>
        /// <param name="usage">The resource usage specifying the type of memory the buffer should use.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the render system is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating underlying buffer fails.</exception>
        public IndexBuffer(IRenderSystemProvider renderSystem, DataBuffer<int> data, ResourceUsage usage) {
            if(renderSystem == null) {
                Dispose();
                throw new ArgumentNullException("renderSystem", "Render system cannot be null.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateIndexBufferImplementation(data, usage);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="IndexBuffer"/>.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <param name="data">The index data.</param>
        /// <param name="usage">The resource usage specifying the type of memory the buffer should use.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the render system is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating underlying buffer fails.</exception>
        public IndexBuffer(IRenderSystemProvider renderSystem, DataBuffer<short> data, ResourceUsage usage) {
            if(renderSystem == null) {
                Dispose();
                throw new ArgumentNullException("renderSystem", "Render system cannot be null.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateIndexBufferImplementation(data, usage);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="IndexBuffer"/> is reclaimed by garbage collection.
        /// </summary>
        ~IndexBuffer() {
            Dispose(false);
        }

        /// <summary>
        /// Writes data from the array to the index buffer.
        /// </summary>
        /// <typeparam name="T">The type of data in the index buffer - int or short.</typeparam>
        /// <param name="data">Array to copy the data from</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if an error occurs while writing to the index buffer</exception>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public void SetData<T>(T[] data) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(data, 0, data.Length, 0, DataWriteOptions.None);
            } catch(Exception e) {
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Writes data from the array to the index buffer.
        /// </summary>
        /// <typeparam name="T">The type of data in the index buffer - int or short.</typeparam>
        /// <param name="data">Array to copy the data from</param>
        /// <param name="writeOptions">Write options, used only if this is a dynamic buffer. None, discard, no overwrite</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if an error occurs while writing to the index buffer</exception>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public void SetData<T>(T[] data, DataWriteOptions writeOptions) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(data, 0, data.Length, 0, writeOptions);
            } catch(Exception e) {
                throw new TeslaException("Error writing to index buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Writes data from the array to the index buffer.
        /// </summary>
        /// <typeparam name="T">The type of data in the index buffer - int or short.</typeparam>
        /// <param name="data">Array to copy the data from</param>
        /// <param name="startIndex">Starting index in the array at which to start copying from</param>
        /// <param name="elementCount">Number of indices to write</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if an error occurs while writing to the index buffer</exception>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public void SetData<T>(T[] data, int startIndex, int elementCount) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(data, startIndex, elementCount, 0, DataWriteOptions.None);
            } catch(Exception e) {
                throw new TeslaException("Error writing to index buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Writes data from the array to the index buffer.
        /// </summary>
        /// <typeparam name="T">The type of data in the index buffer - int or short.</typeparam>
        /// <param name="data">Array to copy the data from</param>
        /// <param name="startIndex">Starting index in the array at which to start copying from</param>
        /// <param name="elementCount">Number of indices to write</param>
        /// <param name="writeOptions">Write options, used only if this is a dynamic buffer. None, discard, no overwrite</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if an error occurs while writing to the index buffer</exception>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public void SetData<T>(T[] data, int startIndex, int elementCount, DataWriteOptions writeOptions) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(data, startIndex, elementCount, 0, writeOptions);
            } catch(Exception e) {
                throw new TeslaException("Error writing to index buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Writes data from the array to the index buffer.
        /// </summary>
        /// <typeparam name="T">The type of data in the index buffer - int or short.</typeparam>
        /// <param name="data">Array to copy the data from</param>
        /// <param name="startIndex">Starting index in the array at which to start copying from</param>
        /// <param name="elementCount">Number of indices to write</param>
        /// <param name="offsetInBytes">Offset from the start of the index buffer at which to start writing at</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if an error occurs while writing to the index buffer</exception>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public void SetData<T>(T[] data, int startIndex, int elementCount, int offsetInBytes) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
            _impl.SetData<T>(data, startIndex, elementCount, offsetInBytes, DataWriteOptions.None);
            } catch(Exception e) {
                throw new TeslaException("Error writing to index buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Writes data from the array to the index buffer.
        /// </summary>
        /// <typeparam name="T">The type of data in the index buffer - int or short.</typeparam>
        /// <param name="data">Array to copy the data from</param>
        /// <param name="startIndex">Starting index in the array at which to start copying from</param>
        /// <param name="elementCount">Number of indices to write</param>
        /// <param name="offsetInBytes">Offset from the start of the index buffer at which to start writing at</param>
        /// <param name="writeOptions">Write options, used only if this is a dynamic buffer. None, discard, no overwrite</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if an error occurs while writing to the index buffer</exception>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public void SetData<T>(T[] data, int startIndex, int elementCount, int offsetInBytes, DataWriteOptions writeOptions) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(data, startIndex, elementCount, offsetInBytes, writeOptions);
            } catch(Exception e) {
                throw new TeslaException("Error writing to index buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Reads data from the index buffer into the array.
        /// </summary>
        /// <typeparam name="T">The type of data in the index buffer - int or short.</typeparam>
        /// <param name="data">Array to write the data to</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if an error occurs while reading from the index buffer</exception>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public void GetData<T>(T[] data) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.GetData<T>(data, 0, data.Length, 0);
            } catch(Exception e) {
                throw new TeslaException("Error reading from index buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Reads data from the index buffer into the array.
        /// </summary>
        /// <typeparam name="T">The type of data in the index buffer - int or short.</typeparam>
        /// <param name="data">Array to write the data to</param>
        /// <param name="startIndex">Starting index in the array at which to start writing to</param>
        /// <param name="elementCount">Number of indices to read</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if an error occurs while reading from the index buffer</exception>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public void GetData<T>(T[] data, int startIndex, int elementCount) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.GetData<T>(data, startIndex, elementCount, 0);
            } catch(Exception e) {
                throw new TeslaException("Error reading from index buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Reads data from the index buffer into the array.
        /// </summary>
        /// <typeparam name="T">The type of data in the index buffer - int or short.</typeparam>
        /// <param name="data">Array to write the data to</param>
        /// <param name="startIndex">Starting index in the array at which to start writing to</param>
        /// <param name="elementCount">Number of indices to read</param>
        /// <param name="offsetInBytes">Offset from the start of the index buffer at which to start copying from</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if an error occurs while reading from the index buffer</exception>
        /// <remarks>See implementors for exceptions that may occur.</remarks>
        public void GetData<T>(T[] data, int startIndex, int elementCount, int offsetInBytes) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.GetData<T>(data, startIndex, elementCount, offsetInBytes);
            } catch(Exception e) {
                throw new TeslaException("Error reading from index buffer: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Serializes the object and writes it to the output.
        /// </summary>
        /// <param name="output">Savable Output</param>
        public void Write(ISavableWriter output) {
            output.Write("Name", base.Name);
            output.Write("IndexCount", _impl.IndexCount);
            output.WriteEnum<IndexFormat>("IndexFormat", _impl.IndexFormat);
            output.WriteEnum<ResourceUsage>("BufferUsage", _impl.BufferUsage);
            int formatBytes = (_impl.IndexFormat == IndexFormat.ThirtyTwoBits) ? 4 : 2;
            byte[] byteBuffer = new byte[_impl.IndexCount * formatBytes];
            output.Write("IndexData", byteBuffer);
        }

        /// <summary>
        /// Deserializes the object and populates it from the input.
        /// </summary>
        /// <param name="input">Savable input</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying implementation fails or the render
        /// system is not set.</exception>
        public void Read(ISavableReader input) {
            IRenderSystemProvider renderSystem = input.RenderSystem;
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;
            String name = input.ReadString();
            int indexCount = input.ReadInt();
            IndexFormat format = input.ReadEnum<IndexFormat>();
            ResourceUsage usage = input.ReadEnum<ResourceUsage>();
            byte[] byteBuffer = input.ReadByteArray();

            try {
                _impl = renderSystem.CreateIndexBufferImplementation(format, indexCount, usage);
                _impl.Name = name;
                SetData<byte>(byteBuffer);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }
    }
}
